
/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup  登录注册
 * @api {POST} api/signin 登录
 * @apiName api/signin
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/signin', {
 *    username: 'gmonking',
 *    password: '123456',
 *  });
 * @apiParam {String} username 用户名称
 * @apiParam {String} password 用户密码
 * @apiSuccess (请求成功) {String} token 用户令牌
 * @apiuse  ErrorResponse
 */

const { query } = require('../../helper/db');
const { encrypt, decrypt, ok } = require('../../helper/util');

module.exports = async ctx => {
  var params = ctx.request.body;
  console.log(params);
  var userlist = await query('select * from user where username = ?', [params.username]);

  if (!userlist.length) {
    throw new Error('该用户不存在');
  }

  var user = userlist[0];
  var encrypedPassword = user.password;
  var password = decrypt('password', encrypedPassword);

  if (params.password !== password) throw new Error('密码错误');

  ctx.body = ok({
    token: encrypt('user', user.id),
  });
}
